package com.by.controller;


import com.by.entity.Member;
import com.by.entity.dto.MemberRegisterDTO;
import com.by.result.Result;
import com.by.service.MemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/member")
@Api(tags = "会员服务")
public class MemberController extends BaseController {
    @Autowired
    MemberService memberService;


    @PostMapping("/register")
    @ApiOperation("会员注册")
    public ResponseEntity<Result<Long>> register(
             @RequestBody MemberRegisterDTO registerDTO,
            BindingResult bindingResult) {

        // 参数校验
        if (bindingResult.hasErrors()) {
            throw new IllegalArgumentException(bindingResult.getFieldError().getDefaultMessage());
        }

        // 密码一致性校验
        if (!registerDTO.getPassword().equals(registerDTO.getConfirmPassword())) {
            return ResponseEntity.badRequest().body(Result.fail("两次输入的密码不一致"));
        }

        // 执行注册
        Long memberId = memberService.register(registerDTO);

        return ResponseEntity.ok(Result.success(memberId));
    }

    @PostMapping("/login")
    @ApiOperation("会员登录")
    public ResponseEntity<Result<Member>> login(
            @RequestBody Member member,
            BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            throw new IllegalArgumentException(bindingResult.getFieldError().getDefaultMessage());
        }
        if (memberService.usernameExists(member.getUsername())) {
            return ResponseEntity.ok(Result.success(member));
        } else {
            return ResponseEntity.badRequest().body(Result.fail("用户名不存在"));
        }
    }

    /**
     * 更新会员信息
     * @param member
     * @param bindingResult
     * @return
     */
    @PostMapping("/update")
    @ApiOperation("更新会员信息")
    public ResponseEntity<Result<Member>> update(
            @RequestBody Member member,
            BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            throw new IllegalArgumentException(bindingResult.getFieldError().getDefaultMessage());
        }
        if (memberService.updateMember(member)) {
            return ResponseEntity.ok(Result.success(member));
        } else {
            return ResponseEntity.badRequest().body(Result.fail("更新会员信息失败"));
        }
    }


}






